using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;

namespace HNet
{
    public class Conn
    {
        //常量
        public const int BufferSize = 1024;

        //Socket
        public Socket socket;

        //是否使用
        public bool IsUse = false;

        //Buff
        public byte[] ReadBuff = new byte[BufferSize];

        public int BuffCount = 0;

        //KCP
        public KCP mKcp;

        public uint Conv;

        public SwitchQueue<byte[]> RecvQueue;

        //UDP
        public UdpClient UDPClient;

        public IPEndPoint IpEndPoint;
        public IPEndPoint ClientEndPoint;

        //构造函数
        public Conn()
        {
            ReadBuff = new byte[BufferSize];
        }

        //初始化
        public void Init(Socket socket)
        {
            this.socket = socket;
            IsUse = true;

            RecvQueue = new SwitchQueue<byte[]>(128);

            BuffCount = 0;
        }

        public void InitKcp(uint conv)
        {
            Conv = conv;
            mKcp = new KCP(conv, (byte[] buf, int size) =>
            {
                //NetLog.S("UDP 发送消息" + size);
                UDPClient.Send(buf, size);
            });

            mKcp.NoDelay(1, NetController.Instance.Interval, 2, 1);
        }

        //缓冲区剩余的字节数
        public int BuffRemain()
        {
            return BufferSize - BuffCount;
        }

        //获取客户端地址
        public string GetAdress()
        {
            if (!IsUse)
                return "无法获取地址";
            return socket.RemoteEndPoint.ToString();
        }

        //关闭
        public void Close()
        {
            if (!IsUse)
                return;

            Console.WriteLine("[断开链接]" + GetAdress());
            socket.Close();
            UDPClient.Close();
            RecvQueue.Clear();
            IsUse = false;
        }
    }
}